package com.ruoyi.framework.websocket.WebSocketServer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

import com.ruoyi.framework.websocket.SemaphoreUtils;
import com.ruoyi.framework.websocket.WebSocketUsers;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception
    {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            // 添加用户
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(session, "连接成功");
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        boolean removeFlag = WebSocketUsers.remove(session.getId());
        if (!removeFlag)
        {
            // 获取到信号量则需释放
            SemaphoreUtils.release(socketSemaphore);
        }
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        String msg = message.replace("你", "我").replace("吗", "");
        WebSocketUsers.sendMessageToUserByText(session, msg);
    }

    // 假设我们存储设备最新的两个点
    private volatile Point lastPoint = new Point(87.62, 43.83 );
    private volatile Point currentPoint = new Point(87.68, 43.88);

    // 插值点列表（预计算）
    private List<Point> interpolatedPoints = new ArrayList<>();

    // 当前插值发送的索引
    private int interpolationIndex = 0;

    // 插值点数量（比如每5秒补4个点，1秒发1个点）
    private final int interpolationCount = 5;

    // 线性插值计算插值点
    private List<Point> interpolate(Point p0, Point p1, int count) {
        List<Point> points = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            double t = i / (double) count;
            double x = p0.x + t * (p1.x - p0.x);
            double y = p0.y + t * (p1.y - p0.y);
            points.add(new Point(x, y));
        }
        return points;
    }
    // 定时任务每秒发送一个坐标点


    // 模拟方法，生成下一个点，这里简单演示向右移动
    private Point getNextPoint() {
        return new Point(currentPoint.x + 100, currentPoint.y);
    }

    // 简单点类
    static class Point {
        double x, y;
        Point(double x, double y) { this.x = x; this.y = y; }
    }
}
